package com.yjj.demo.common.web;

import com.yjj.demo.common.exception.NoStackException;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 *
 *
 * @author yangjiajia
 * @time 2021/9/25 15:02
 */
@RestControllerAdvice
@Log4j2
public class AbsController {

    @ExceptionHandler(Exception.class)
    protected String exceptionHandle(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return "未捕获异常:" + e.getMessage();
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    protected String requestException(HttpMessageNotReadableException e) {
        return "请求参数不能为空";
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    protected String requestException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        return errors.get(0).getDefaultMessage();
    }

    @ExceptionHandler(NoStackException.class)
    public String noStackException(NoStackException e) {
        log.error(e.getMessage());
        return e.getMessage();
    }
}
